<template>
    <div class="madp-authorization-management">
        <basic-container v-loading="loading">
            <div>
                <el-button type="primary" @click="addNew" v-if="showAdd && permissions.sys_crop_add">+ 添加企业微信号</el-button>
            </div>
            <!-- 表格 -->
            <div class="madp-table">
                <el-table
                    :data="tableData"
                    :header-cell-style="{
                        background: 'rgb(255, 191, 191)',
                        color: 'rgb(44,44,44)'
                    }"
                    :stripe="true"
                >
                    <el-table-column type="index" label="序号" align="center" width="70">
                        <template slot-scope="scope">
                            <span v-text="getIndex(scope.$index)"></span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="corpName" label="企业名称" align="center"></el-table-column>
                    <el-table-column prop="wxCorpId" label="企业ID" align="center"></el-table-column>
                    <el-table-column prop="messageCreateTime" label="绑定时间" align="center"></el-table-column>
                    <el-table-column label="操作" align="center">
                        <template slot-scope="scope">
                            <el-button @click.native.prevent="showRow(scope.row)" type="text">查看</el-button>
                            <el-button v-if="permissions.sys_crop_edit" @click.native.prevent="editRow(scope.row)" type="text">编辑</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 添加企业微信号 -->
            <el-dialog title="添加企业微信号" :visible.sync="addDialog" :close-on-click-modal="false" :before-close="addCancel">
                <el-form :model="addForm" ref="addForm" :rules="addRules1" label-width="200px">
                    <el-form-item label="企业名称" prop="corpName">
                        <el-input v-model.trim="addForm.corpName" autocomplete="off" maxlength="20" @input="addForm.corpName = checkCorpName(addForm.corpName)" placeholder="请输入企业名称"></el-input>
                    </el-form-item>
                    <el-form-item label="企业ID" prop="wxCorpId">
                        <el-input
                            maxlength="50"
                            v-model.trim="addForm.wxCorpId"
                            @input="addForm.wxCorpId = addForm.wxCorpId.replace(/[^A-Za-z0-9]/g, '')"
                            autocomplete="off"
                            placeholder="请输入企业ID"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="通讯录管理secret" prop="employeeSecret">
                        <el-input
                            v-model.trim="addForm.employeeSecret"
                            autocomplete="off"
                            @input="addForm.employeeSecret = addForm.employeeSecret.replace(/[\u4E00-\u9FA5]/g, '')"
                            maxlength="50"
                            placeholder="请输入通讯录管理secret"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="外部联系人管理secret" prop="contactSecret">
                        <el-input
                            v-model.trim="addForm.contactSecret"
                            autocomplete="off"
                            @input="addForm.contactSecret = addForm.contactSecret.replace(/[\u4E00-\u9FA5]/g, '')"
                            maxlength="50"
                            placeholder="请输入外部联系人管理secret"
                        ></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer">
                    <el-button @click="addCancel">取消</el-button>
                    <el-button type="primary" :loading="submitLoading" @click="addConfirm">确定</el-button>
                </div>
            </el-dialog>

            <!-- 查看/编辑企业微信号 -->
            <el-dialog :title="dialogTitle" :visible.sync="dialog" :close-on-click-modal="false" :before-close="oCancel" v-if="dialog">
                <el-tabs v-model="activeName" type="card" :stretch="true">
                    <el-tab-pane label="基本信息" name="first">
                        <div class="madp-form">
                            <el-form :model="showInfo" ref="showInfo1" :rules="addRules1" label-width="220px">
                                <!-- 1111 -->
                                <el-form-item label="企业名称" prop="corpName">
                                    <el-input
                                        :disabled="dialogType === 'show'"
                                        v-model.trim="showInfo.corpName"
                                        autocomplete="off"
                                        maxlength="20"
                                        @input="showInfo.corpName = checkCorpName(showInfo.corpName)"
                                        placeholder="请输入企业名称"
                                    ></el-input>
                                </el-form-item>
                                <el-form-item label="企业ID" prop="wxCorpId">
                                    <el-input
                                        :disabled="dialogType === 'show'"
                                        maxlength="50"
                                        v-model.trim="showInfo.wxCorpId"
                                        autocomplete="off"
                                        @input="showInfo.wxCorpId = showInfo.wxCorpId.replace(/[^A-Za-z0-9]/g, '')"
                                        placeholder="请输入企业ID"
                                    ></el-input>
                                </el-form-item>
                                <el-form-item label="通讯录管理secret" prop="employeeSecret">
                                    <el-input
                                        :disabled="dialogType === 'show'"
                                        v-model.trim="showInfo.employeeSecret"
                                        autocomplete="off"
                                        maxlength="50"
                                        @input="showInfo.employeeSecret = showInfo.employeeSecret.replace(/[\u4E00-\u9FA5]/g, '')"
                                        placeholder="请输入通讯录管理secret"
                                    ></el-input>
                                </el-form-item>
                                <el-form-item label="外部联系人管理secret" prop="contactSecret">
                                    <el-input
                                        :disabled="dialogType === 'show'"
                                        v-model.trim="showInfo.contactSecret"
                                        autocomplete="off"
                                        max="50"
                                        @input="showInfo.contactSecret = showInfo.contactSecret.replace(/[\u4E00-\u9FA5]/g, '')"
                                        placeholder="请输入外部联系人管理secret"
                                    ></el-input>
                                </el-form-item>
                            </el-form>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="通讯录接收" name="second">
                        <div class="madp-form">
                            <el-form :model="showInfo" ref="showInfo2" label-width="220px">
                                <el-form-item label="通讯录事件服务器URL" prop="eventCallback">
                                    <el-input
                                        :disabled="dialogType === 'show'"
                                        v-model.trim="showInfo.eventCallback"
                                        @input="showInfo.eventCallback = showInfo.eventCallback.replace(/\s+/g, '')"
                                        placeholder="请输入通讯录事件服务器URL"
                                        autocomplete="off"
                                        maxlength="300"
                                    ></el-input>
                                </el-form-item>
                                <el-form-item label="Token" prop="token">
                                    <el-input
                                        :disabled="dialogType === 'show'"
                                        v-model.trim="showInfo.token"
                                        @input="showInfo.token = showInfo.token.replace(/\s+/g, '')"
                                        autocomplete="off"
                                        placeholder="请输入Token"
                                    ></el-input>
                                </el-form-item>
                                <el-form-item label="EncodingAESKey" prop="encodingAesKey">
                                    <el-input
                                        :disabled="dialogType === 'show'"
                                        v-model.trim="showInfo.encodingAesKey"
                                        @input="showInfo.encodingAesKey = showInfo.encodingAesKey.replace(/\s+/g, '')"
                                        autocomplete="off"
                                        placeholder="请输入EncodingAESKey"
                                    ></el-input>
                                </el-form-item>
                            </el-form>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="外部联系人接收" name="third">
                        <div class="madp-form">
                            <el-form :model="showInfo" ref="showInfo3" label-width="220px">
                                <el-form-item label="外部联系人事件服务器URL" prop="eventCallback">
                                    <el-input
                                        :disabled="dialogType === 'show'"
                                        v-model.trim="showInfo.eventCallback"
                                        @input="showInfo.eventCallback = showInfo.eventCallback.replace(/\s+/g, '')"
                                        autocomplete="off"
                                        placeholder="请输入外部联系人事件服务器URL"
                                    ></el-input>
                                </el-form-item>
                                <el-form-item label="Token" prop="token">
                                    <el-input
                                        :disabled="dialogType === 'show'"
                                        v-model.trim="showInfo.token"
                                        @input="showInfo.token = showInfo.token.replace(/\s+/g, '')"
                                        autocomplete="off"
                                        placeholder="请输入Token"
                                    ></el-input>
                                </el-form-item>
                                <el-form-item label="EncodingAESKey" prop="encodingAesKey">
                                    <el-input
                                        :disabled="dialogType === 'show'"
                                        v-model.trim="showInfo.encodingAesKey"
                                        @input="showInfo.encodingAesKey = showInfo.encodingAesKey.replace(/\s+/g, '')"
                                        autocomplete="off"
                                        placeholder="请输入EncodingAESKey"
                                    ></el-input>
                                </el-form-item>
                            </el-form>
                        </div>
                    </el-tab-pane>
                </el-tabs>
                <div slot="footer" v-show="dialogType === 'edit'">
                    <el-button @click="oCancel">取消</el-button>
                    <el-button type="primary" :loading="editLoading" @click="oConfirm">确定</el-button>
                </div>
                <div slot="footer" v-show="dialogType === 'show'">
                    <el-button @click="oCancel">关闭</el-button>
                </div>
            </el-dialog>
        </basic-container>
    </div>
</template>

<script>
import { postEnterpriseInfo, getEnterpriseInfoList, getDetails, putEnterpriseInfo, postBind, putDefaultCorp } from '@/api/company-manage/authorization';
import { mapGetters } from 'vuex';
export default {
    name: 'authorizationManagement',
    data() {
        // 校验 外部联系人事件服务器URL
        let checkContactURL = (rule, value, callback) => {
            let URLReg = /(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;
            // 没有值的表单，value为undefined
            if (value === undefined || value.length === 0) {
                callback();
            } else if (!URLReg.test(value)) {
                callback(new Error('请输入正确URL'));
            } else {
                callback();
            }
        };
        return {
            showAdd: false, // 显示新增按钮开关
            loading: false, // loading开关
            activeName: 'first', // tab显示开关
            // 分页
            page: {
                total: 0, // 总页数
                currentPage: 1, // 当前页数
                pageSize: 10 // 每页显示多少条
            },
            corpName: '', // 企业名称
            tableData: [], // 列表数据
            addDialog: false, // 新增弹框
            // 新增表单对象
            addForm: {
                corpName: '',
                wxCorpId: '',
                employeeSecret: '',
                contactSecret: ''
            },
            // 表单校验规则
            addRules1: {
                corpName: [
                    {
                        required: true,
                        message: '请输入企业名称',
                        trigger: 'blur'
                    }
                ],
                wxCorpId: [
                    {
                        required: true,
                        message: '请输入企业ID',
                        trigger: 'blur'
                    }
                ],
                employeeSecret: [
                    {
                        required: true,
                        message: '请输入通讯录管理secret',
                        trigger: 'blur'
                    }
                ],
                contactSecret: [
                    {
                        required: true,
                        message: '请输入外部联系人管理secret',
                        trigger: 'blur'
                    }
                ]
            },
            dialog: false, // 查看和编辑的弹框
            // 显示信息
            showInfo: {
                corpName: '',
                wxCorpId: '',
                employeeSecret: '',
                contactSecret: '',
                token: '',
                encodingAesKey: '',
                eventCallback: ''
            }, // 存储点击查看/编辑的信息
            dialogType: '', // 区分查看/编辑
            submitLoading: false,
            dialogTitle: '', // 弹窗标题
            editLoading: false // loading开关
        };
    },
    computed: {
        ...mapGetters(['permissions'])
    },
    mounted() {
        this.getList();
    },
    methods: {
        // 检查姓名
        checkCorpName(val) {
            let acount = /[\u4E00-\u9FA5]/g,
                str = '';
            str = val.match(acount);
            if (str && str.length > 0) {
                str = str.join('');
            } else {
                str = '';
            }
            return str;
        },
        //获取表格序号
        getIndex($index) {
            return $index + 1;
        },
        //获取企业信息列表 page分页参数，params 查询参数
        getList() {
            this.loading = true;
            let obj = {
                current: 1,
                size: 10
            };
            if (this.corpName) obj = { ...obj, corpName: this.corpName };
            getEnterpriseInfoList(obj)
                .then((res) => {
                    if (res.data.code === 0) {
                        this.tableData = res.data.data.records;
                        this.showAdd = this.tableData.length == 0;
                    }
                    this.loading = false;
                })
                .catch(() => {
                    this.loading = false;
                });
        },
        // 新增
        addNew() {
            this.addDialog = true;
        },
        // 新增弹框里面取消按钮
        addCancel() {
            this.addDialog = false;
            this.$refs['addForm'].resetFields();
        },
        // 新增弹框里面确认按钮
        addConfirm() {
            this.$refs['addForm'].validate((valid) => {
                if (valid) {
                    this.submitLoading = true;
                    postEnterpriseInfo(this.addForm)
                        .then((res) => {
                            this.submitLoading = false;
                            if (res.data.code === 0) {
                                this.$message({
                                    type: 'success',
                                    message: '创建成功'
                                });
                                this.addDialog = false;
                                this.getList();
                                this.$refs['addForm'].resetFields();
                                postBind().then(() => {});
                            }
                        })
                        .catch(() => {
                            this.submitLoading = false;
                        });
                } else {
                    this.submitLoading = false;
                    return false;
                }
            });
        },
        // 查看
        showRow(row) {
            this.dialogTitle = '查看企业微信号';
            this.getEnterpriseInfoDetails(row.corpId);
            this.currentMenu = 1;
            this.dialog = true;
            this.dialogType = 'show';
        },
        // 编辑
        editRow(row) {
            this.dialogTitle = '编辑企业微信号';
            this.getEnterpriseInfoDetails(row.corpId);
            this.currentMenu = 1;
            this.dialog = true;
            this.dialogType = 'edit';
        },
        //获取企业信息详情
        getEnterpriseInfoDetails(corpId) {
            getDetails(corpId)
                .then((res) => {
                    if (res.data.code === 0) {
                        this.showInfo = res.data.data;
                    }
                })
                .catch(() => {});
        },
        // 编辑弹框 取消按钮
        oCancel() {
            this.$refs['showInfo1'].clearValidate();
            this.$refs['showInfo2'].clearValidate();
            this.$refs['showInfo3'].clearValidate();
            this.dialog = false;
        },
        // 编辑弹框 确定按钮
        oConfirm() {
            this.$refs['showInfo1'].validate((valid) => {
                if (valid) {
                    // 验证通过
                    this.editLoading = true;
                    putEnterpriseInfo(this.showInfo)
                        .then((res) => {
                            this.editLoading = false;
                            if (res.data.code === 0) {
                                this.$message({
                                    type: 'success',
                                    message: '编辑成功！'
                                });
                                this.getList();
                                this.dialog = false;
                                this.$refs['showInfo1'].clearValidate();
                                this.$refs['showInfo2'].clearValidate();
                                this.$refs['showInfo3'].clearValidate();
                            } else {
                                this.$message({
                                    type: 'error',
                                    message: res.data.msg
                                });
                            }
                        })
                        .catch(() => {
                            this.editLoading = false;
                        });
                } else {
                    this.editLoading = false;
                    return false;
                }
            });
        },
        // 切换默认开关
        toggle(index, row) {
            if (!row.defaultEnable) {
                this.$message({
                    type: 'info',
                    message: '不能更改已设为默认企业微信号的企业微信号状态'
                });
                this.tableData[index].defaultEnable = true;
                return;
            }
            // 开启提示
            this.$confirm('设置当前企业微信号为默认账号，其他企业微信号将默认设置为非默认，确认是否设置？', '温馨提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            })
                .then(() => {
                    //启用默认接口
                    putDefaultCorp({ corpId: row.corpId }).then((res) => {
                        if (res.data.code === 0) {
                            this.$message({
                                type: 'success',
                                message: '设置成功'
                            });
                            this.getList();
                        }
                    });
                })
                .catch(() => {
                    this.tableData[index].defaultEnable = !this.tableData[index].defaultEnable;
                });
        }
    }
};
</script>

<style lang="scss" scoped>
.madp-authorization-management {
    // 头部输入框
    .madp-left-content-one {
        float: right;
        margin-right: 10px;
    }
    .madp-left-content-input {
        width: 200px;
    }
    .madp-table {
        margin-top: 20px;
    }
    // 头部按钮
    .madp-right-content {
        float: right;
    }

    .madp-menu-font {
        color: black;
    }
    .madp-menu-title {
        cursor: pointer;
    }
    // 分页
    .madp-pagination-wrap {
        float: right;
        margin-top: 30px;
        margin-bottom: 18px;
    }
}
.madp-form {
    margin-top: 25px;
}
</style>
